package com.finance41.webtools.automerge;

import java.io.File;
import java.util.Date;

/**
 * Watches a set of files and, when one of them is modified, it merges the files. The output is written to a given file.
 * If one of the input files is a directory, then the files from that directory are watched and merged.
 * Additional processing can be performed on the merged content before writing it to the output file
 * by extending this class and overwriting the {@link #process(String)} method.
 * If "versioned" is true, the parent directory of the output file is cleaned before the outputFile is written, and the outputFile name is
 * modified by appending "-timestamp" before the file extension (E.g.: out.css becomes out-1213323232.css).
 *
 * @author Ionut Bilica
 */
public class FilesAutoMerger {

	public void autoMerge(final File[] inputFiles, final File outputFile, final boolean versioned) {
		for (File file : inputFiles) {
			FileWatcher fileWatcher = new FileWatcher();
			fileWatcher.watch(file, new Action() {
				@Override
				public void perform() {
					merge(inputFiles, outputFile, versioned);
				}
			});
		}
	}

	private void merge(File[] inputFiles, File outputFile, boolean versioned) {
		String content = process(FileUtil.mergeFiles(inputFiles));

		if (versioned) {
			FileUtil.removeAllFiles(outputFile.getParentFile());
			String[] fileParts = outputFile.getAbsolutePath().split("\\.");
			outputFile = new File(fileParts[0] + "-" + ((new Date()).getTime() / 1000) + "." + fileParts[1]);
		}

		FileUtil.setFileContent(outputFile, content);
		System.out.println((new Date().getTime())/1000 + " merge " + outputFile.getAbsolutePath());
	}

	protected String process(String content) {
		return content;
	}
}
